package com.dewod.producesales.utils.request;

import android.util.Log;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.dewod.producesales.utils.HttpUtil;
import com.google.firebase.crashlytics.buildtools.reloc.org.apache.http.message.BasicNameValuePair;

import org.json.JSONException;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class RequestBaseUtil {

    public static String baseUrl;

    public interface CallBack<T> {

        void action(T t) throws JSONException;
    }


    public interface ExceptionCallBack<T> {
        void action(T t);
    }

    static String doRequest(ApiEnums apiEnum, Serializable form){
        String method = apiEnum.getMethod();
        if (StringUtils.equals("get", method)) {
            List<BasicNameValuePair> params = toParam(form);
            return HttpUtil.get(baseUrl, apiEnum.getUrlSuffix(), params, null, null);
        } else {
            return HttpUtil.doJsonPost(baseUrl, apiEnum.getUrlSuffix(), form);
        }
    }


    private static List<BasicNameValuePair> toParam(Object o) {
        List<BasicNameValuePair> result = null;
        try {
            result = new ArrayList<>();
            Class<?> aClass = o.getClass();
            for (Field field : aClass.getDeclaredFields()) {
                field.setAccessible(true);
                Object fieldValue = field.get(o);
                if (ObjectUtils.isEmpty(fieldValue)) {
                    continue;
                }
                String value;
                if (fieldValue instanceof List) {
                    value = GsonUtils.toJson(fieldValue);
                } else {
                    value = String.valueOf(fieldValue);
                }
                result.add(new BasicNameValuePair(field.getName(), value));
            }
        } catch (IllegalAccessException e) {
            Log.e("request", "===========================>" + e);
        }
        return result;
    }


}
